package com.demo.fullink.rabbitmq;

import com.alibaba.fastjson.JSON;
import com.demo.fullink.config.RabbitConfig;
import com.demo.fullink.service.AsyncOrderService;
import com.demo.fulllink.module.vo.OrderVO;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

/**
 * 订单消费者类
 */
@Component
public class MQConsumer {
    
    @Autowired
    private AsyncOrderService asyncOrderService;
    
    @RabbitListener(
            bindings =
                    {
                            @QueueBinding(value = @Queue(value = RabbitConfig.PLACE_ORDER_QUEUE, durable = "true"),
                                    exchange = @Exchange(value = RabbitConfig.PLACE_ORDER_QUEUE_EXCHANGE), key = RabbitConfig.PLACE_ORDER_KEY)
                    })
    @RabbitHandler
    public void processOrder(Message massage, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long tag) {
        OrderVO orderVO = JSON.parseObject(massage.getBody(), OrderVO.class);
        try {
            //开始处理订单
            asyncOrderService.processOrder(orderVO);
            //手动确认机制
            channel.basicAck(tag, false);
        } catch (Exception e) {
            e.printStackTrace();
        }
        
    }
}
